package cn.elead.it.template.config;

import java.util.List;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import cn.elead.it.common.spring.IEnumConverterFactory;
import cn.elead.it.common.spring.validator.ValidatorCollectionImpl;
import cn.elead.it.common.util.JacksonUtils;
import cn.elead.it.template.exception.TemplateHandlerExceptionResolver;

/**
 * <p>
 * Spring Boot MVC配置
 * </p>
 *
 * @author luopeng
 */
@Configuration
public class WebMvcAutoConfiguration implements WebMvcConfigurer {


	@Override
	public Validator getValidator() {
		return new SpringValidatorAdapter(new ValidatorCollectionImpl());
	}

	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addConverterFactory(new IEnumConverterFactory());
	}

	@Bean
	@ConditionalOnMissingBean(RequestContextListener.class)
	public RequestContextListener requestContextListener() {
		return new RequestContextListener();
	}

	@Override
	public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
		converters.forEach(JacksonUtils.wrapperObjectMapper());
	}

	@Override
	public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
		exceptionResolvers.add(new TemplateHandlerExceptionResolver());
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		WebMvcConfigurer.super.addResourceHandlers(registry);
	}

	@Override
	public void addCorsMappings(CorsRegistry registry) {
		// https://segmentfault.com/a/1190000018554528?utm_source=tag-newest
		// 添加映射路径,允许跨域访问的路径
		registry.addMapping("/**")
				// 放行哪些原始域,允许跨域访问的源
				.allowedOrigins("*")
				// 是否发送Cookie信息
				.allowCredentials(true)
				// 放行哪些原始域,允许请求方法(请求方式)
				.allowedMethods("GET", "POST", "PUT", "DELETE")
				// 放行哪些原始域,允许头部设置(头部信息)
				.allowedHeaders("*")
				// 暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
				.exposedHeaders("Header1", "Header2");
	}

}
